package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.*;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.*;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.goods.SpuService;
import com.qingcheng.util.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service(interfaceClass = SpuService.class)
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    /**
     * 返回全部记录
     * @return
     */
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Spu> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectAll();
        return new PageResult<Spu>(spus.getTotal(),spus.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectByExample(example);
        return new PageResult<Spu>(spus.getTotal(),spus.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Spu findById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param spu
     */
    public void add(Spu spu) {
        spuMapper.insert(spu);
    }

    /**
     * 修改
     * @param spu
     */
    public void update(Spu spu) {
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        spuMapper.deleteByPrimaryKey(id);
    }

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private IdWorker idWorker;
    
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /////////////////////////////////////////////////////////////////////////////////////////////

    @Autowired
    private SkuService skuService;

    /**
     * 保存商品
     *
     * @param goods 商品组合实体类
     */
    @Override
    @Transactional
    public void saveGoods(Goods goods) {
        //保存一个spu的信息
        Spu spu = goods.getSpu();
        if(spu.getId()==null){ //新增商品
            spu.setId(idWorker.nextId()+"");
            spuMapper.insert(spu);
        }else{ //修改商品
            //删除原来的sku列表
            Example example = new Example(Sku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId",spu.getId());
            skuMapper.deleteByExample(example);
            //执行spu的修改
            spuMapper.updateByPrimaryKeySelective(spu);
        }

        Date date = new Date();
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());

        //保存sku列表的信息
        List<Sku> skuList = goods.getSkuList();

        for(Sku sku:skuList){

            if(sku.getId()==null){//新增sku
                sku.setId(idWorker.nextId()+"");
                sku.setCreateTime(date);//创建日期
            }

            sku.setSpuId(spu.getId());

            //sku名称 = spu名称+规格值列表
            String name = spu.getName();

            //不启用规格的sku处理
            if(sku.getSpec()==null||"".equals(sku.getSpec())){
                sku.setSpec("{}");
            }

            //sku.getSpec() {"颜色":"绿","机身内存":"8G"}
            Map<String,String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
            for(String value: specMap.values()){
                name+=" "+value;
            }
            sku.setName(name);//名称
            sku.setUpdateTime(date);//修改日期
            sku.setCategoryId(spu.getCategory3Id());//分类id
            sku.setCategoryName(category.getName());//分类名称
            sku.setCommentNum(0);//评论数
            sku.setSaleNum(0);//销售数量

            skuMapper.insert(sku);

            //重新将价格更新到缓存
            skuService.savePriceToRedisById(sku.getId(),sku.getPrice());
        }

        //建立分类和品牌的关联
        CategoryBrand categoryBrand = new CategoryBrand();
        categoryBrand.setBrandId(spu.getBrandId());
        categoryBrand.setCategoryId(spu.getCategory3Id());
        int count = categoryBrandMapper.selectCount(categoryBrand);
        if(count==0){
            categoryBrandMapper.insert(categoryBrand);
        }
    }

    /**
     * 根据ID查询商品
     *
     * @param id
     * @return
     */
    @Override
    public Goods findGoodsById(String id) {

        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);

        //查询sku列表
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<Sku> skuList = skuMapper.selectByExample(example);

        //封装，返回
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skuList);

        return goods;
    }

    @Autowired
    private ProductlogMapper productlogMapper;

    /**
     * 商品审核
     *
     * @param id
     * @param status
     * @param message
     */
    @Transactional
    public void audit(String id, String status, String message) {
        //1.修改状态 审核状态和上架状态
        Spu spu = new Spu();
        spu.setId(id);
        spu.setStatus(status);
        if("1".equals(status)){
            spu.setIsMarketable("1");//自动上架
        }
        spuMapper.updateByPrimaryKeySelective(spu);

        //2.记录商品审核记录
        Audit audit = new Audit();
        audit.setId(idWorker.nextId()+"");
        //因为现在还没有上线,故初期将不会采用session域取出用户信息
        audit.setAuditor("Admin");
        audit.setAuditTime(new Date());
        audit.setSpuId(id);
        if("0".equals(status)){//审核未通过
            audit.setMessage(message);
        }

        //3.记录商品日志(后续可基于Aop实现)本地的没写完，价格等没写
        Productlog productlog = new Productlog();
        productlog.setId(idWorker.nextId()+"");
        productlog.setSpuId(id);
        productlog.setAuditor(audit.getAuditor());
        productlog.setAuditTime(audit.getAuditTime());
        productlog.setIsMarketableBef("0");
        productlog.setIsMarketableBef("1");
        productlog.setStatusBef("0");
        productlog.setStatusNow("1");
        productlogMapper.insert(productlog);
    }

    /**
     * 下架商品
     *
     * @param id
     */
    @Override
    public void pull(String id) {
        //1.修改状态
        Spu spu = spuMapper.selectByPrimaryKey(id);
        spu.setIsMarketable("0");//下架状态
        spuMapper.updateByPrimaryKeySelective(spu);

        //发送给rabbitMq消息队列
        //删除商品详细页和删除elasticsearch索引数据，createInde需要skuList，createPage需要goods,和categoryList，将它们转化为json数据发送给rabbitmq
        String spuId=id;
        //1.查询商品详情
        Goods goods = findGoodsById(spuId);
        //2.查询商品分类
        List<String> categoryList = new ArrayList<>();
        categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());//一级分类
        categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());//二级分类
        categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());//三级分类

        //将goods，categoryList放入到map,再转化为jsonString
        Map<String,Object> map = new HashMap<>();
        map.put("goods",goods);
        map.put("categoryList",categoryList);
        map.put("spuId",spuId);

        String mapJsonString = JSON.toJSONString(map);
        rabbitTemplate.convertAndSend("exchange.goods_down","",mapJsonString);



        //2.记录商品日志(后续可基于Aop实现)本地的没写完，价格等没写
        Example example = new Example(Productlog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<Productlog> productlogs = productlogMapper.selectByExample(example);
        for(Productlog productlog :productlogs){
            Productlog productlog1 = new Productlog();
            productlog1.setId(idWorker.nextId()+"");
            productlog1.setSpuId(id);
            productlog1.setIsMarketableBef(productlog.getIsMarketableNow());
            productlog1.setIsMarketableNow("0");
            productlog1.setStatusBef(productlog.getStatusNow());//从之前的productLog日志获取旧数据
            productlog1.setStatusNow("0");
            productlogMapper.insert(productlog);
        }
    }

    @Autowired
    private CategoryService categoryService;
    /**
     * 上架商品
     *
     * @param id
     */
    @Override
    public void put(String id) {
        //1.修改状态
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(!"1".equals(spu.getStatus())){
            throw new RuntimeException("此商品未通过审核");
        }
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);

        //发送给rabbitMq消息队列
        //生成商品详细页和新增elasticsearch索引数据，createInde需要skuList，createPage需要goods,和categoryList，将它们转化为json数据发送给rabbitmq
        String spuId=id;
        //1.查询商品详情
        Goods goods = findGoodsById(spuId);
        //2.查询商品分类
        List<String> categoryList = new ArrayList<>();
        categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());//一级分类
        categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());//二级分类
        categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());//三级分类

        //将goods，categoryList放入到map,再转化为jsonString
        Map<String,Object> map = new HashMap<>();
        map.put("goods",goods);
        map.put("categoryList",categoryList);
        map.put("spuId",spuId);

        String mapJsonString = JSON.toJSONString(map);

        rabbitTemplate.convertAndSend("exchange.goods_up","",mapJsonString);


        //2.记录商品日志(后续可基于Aop实现)本地的没写完，价格等没写
        Example example = new Example(Productlog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<Productlog> productlogList = productlogMapper.selectByExample(example);
        for(Productlog productlog :productlogList){
            Productlog productlog1 = new Productlog();
            productlog1.setId(idWorker.nextId()+"");
            productlog1.setSpuId(id);
            productlog1.setIsMarketableBef(productlog.getIsMarketableNow());
            productlog1.setIsMarketableNow("1");
            productlog1.setStatusBef(productlog.getStatusNow());//从之前的productLog日志获取旧数据
            productlog1.setStatusNow("1");
            productlogMapper.insert(productlog);
        }
    }

    /**
     * 批量上架商品
     *
     * @param ids
     * @return
     */
    @Override
    public int putMany(String[] ids) {
        //1.修改状态
        Spu spu = new Spu();
        spu.setIsMarketable("1");

        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(ids));
        criteria.andEqualTo("isMarketable","0");//下架的
        criteria.andEqualTo("status","1");//审核通过的

        int count = spuMapper.updateByExampleSelective(spu, example);

        //批量生成商品详细页和新增elasticsearch索引数据 , 日志在下架商品中做了
        for(String spuId: ids){
            //1.查询商品详情
            Goods goods = findGoodsById(spuId);
            //2.查询商品分类
            List<String> categoryList = new ArrayList<>();
            categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());//一级分类
            categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());//二级分类
            categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());//三级分类

            //将goods，categoryList放入到map,再转化为jsonString
            Map<String,Object> map = new HashMap<>();
            map.put("goods",goods);
            map.put("categoryList",categoryList);
            map.put("spuId",spuId);

            String mapJsonString = JSON.toJSONString(map);

            rabbitTemplate.convertAndSend("exchange.goods_up","",mapJsonString);
        }

        //2.添加商品日志(后续可基于Aop实现)本地的没写完，价格等没写
        for(String id:ids){
            Example example2 = new Example(Productlog.class);
            Example.Criteria criteria2 = example.createCriteria();
            criteria.andEqualTo("spuId",id);
            List<Productlog> productlogList = productlogMapper.selectByExample(example);
            for(Productlog productlog :productlogList) {
                Productlog productlog1 = new Productlog();
                productlog1.setId(idWorker.nextId()+"");
                productlog1.setSpuId(id);
                productlog1.setIsMarketableBef(productlog.getIsMarketableNow());
                productlog1.setIsMarketableNow("1");
                productlog1.setStatusBef(productlog.getStatusNow());//从之前的productLog日志获取旧数据
                productlog1.setStatusNow("1");
                productlogMapper.insert(productlog);
            }
        }

        return count;
    }

    /**
     * 批量下架商品
     *
     * @param ids
     * @return
     */
    @Override
    public int pullMany(String[] ids) {
        //1.修改状态
        Spu spu = new Spu();
        spu.setIsMarketable("0");

        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(ids));
        criteria.andEqualTo("isMarketable", "1");//上架的

        int count = spuMapper.updateByExampleSelective(spu, example);

        //批量删除商品详细页和删除elasticsearch索引数据, 日志在下架商品中做了
        for (String spuId : ids) {
            //1.查询商品详情
            Goods goods = findGoodsById(spuId);
            //2.查询商品分类
            List<String> categoryList = new ArrayList<>();
            categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());//一级分类
            categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());//二级分类
            categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());//三级分类

            //将goods，categoryList放入到map,再转化为jsonString
            Map<String,Object> map = new HashMap<>();
            map.put("goods",goods);
            map.put("categoryList",categoryList);
            map.put("spuId",spuId);

            String mapJsonString = JSON.toJSONString(map);
            rabbitTemplate.convertAndSend("exchange.goods_down","",mapJsonString);
        }

        //2.添加商品日志(后续可基于Aop实现)本地的没写完，价格等没写
        for(String id:ids){
            Example example2 = new Example(Productlog.class);
            Example.Criteria criteria2 = example.createCriteria();
            criteria.andEqualTo("spuId",id);
            List<Productlog> productlogs = productlogMapper.selectByExample(example);
            for(Productlog productlog :productlogs){
                Productlog productlog1 = new Productlog();
                productlog1.setId(idWorker.nextId()+"");
                productlog1.setSpuId(id);
                productlog1.setIsMarketableBef(productlog.getIsMarketableNow());
                productlog1.setIsMarketableNow("0");
                productlog1.setStatusBef(productlog.getStatusNow());//从之前的productLog日志获取旧数据
                productlog1.setStatusNow("0");
                productlogMapper.insert(productlog);
            }
        }

        return count;
    }

    /**
     * 逻辑删除商品
     *
     * @param id
     */
    @Override
    public void deleteLogic(String id) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setIsDelete("1");
        spuMapper.updateByPrimaryKeySelective(spu);
        
        //删除价格缓存
        Map map=new HashMap();
        map.put("spuId",id);
        List<Sku> skuList = skuService.findList(map);
        for(Sku sku:skuList){
            skuService.deletePriceFromRedisById(sku.getId());
        }

    }

    /**
     * 还原商品
     *
     * @param id
     */
    @Override
    public void saveLogic(String id) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setIsDelete("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 物理删除商品
     *
     * @param id
     */
    @Override
    public void deleteGoods(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(spu.getIsDelete().equals("0")){
            throw new RuntimeException("此商品未删除过,不能物理删除");
        }
        spuMapper.deleteByPrimaryKey(id);
    }

    /////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andLike("sn","%"+searchMap.get("sn")+"%");
            }
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
            }
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
            }
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
            }
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
            }
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
            }
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
            }
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
            }
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
            }
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andLike("isMarketable","%"+searchMap.get("isMarketable")+"%");
            }
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andLike("isEnableSpec","%"+searchMap.get("isEnableSpec")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andLike("status","%"+searchMap.get("status")+"%");
            }

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
